﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Logging;
using System.Threading;
using System.Collections;

namespace Zeny.Basedata.Sync
{
    public class CacheSyncManager
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(CacheSyncManager));

        public ArrayList cacheSyncList {set; get;}

        private int defaultSleepSeconds = 10;
        private bool forceStop = false;
        public int sleepSeconds {set; get; }

        public CacheSyncManager()
        {
            Console.WriteLine("Console.WriteLine");
            log.Info("log.Info");
        }

        public void init()
        {
            if ((cacheSyncList == null) || (cacheSyncList.Count == 0))
            {
                log.Error("缓存列表为空。");
                return;
            }

            ThreadStart threadStart = new ThreadStart(sync);
            Thread thread = new Thread(threadStart);
            thread.Start();
        }

        public void sync()
        {
            log.Info("缓存同步线程已启动。");

            while (!forceStop)
            {
                log.Info("缓存同步线程开始执行");
                if (!((cacheSyncList == null) || (cacheSyncList.Count == 0)))
                {
                    foreach (ICacheSync cacheSync in cacheSyncList)
                    {
                        int syncCount = cacheSync.sync();
                        log.Info(cacheSync + "本次同步" + syncCount + "条。");
                    }
                }
                else
                {
                    log.Error("缓存列表为空。");
                }

                sleepSeconds = sleepSeconds == 0 ? defaultSleepSeconds : sleepSeconds;

                log.Info(this + "休眠" + sleepSeconds + "秒。");
                Thread.Sleep(sleepSeconds * 1000);
            }

            log.Info("缓存同步线程已停止。");
        }

        public void destroy()
        {
            forceStop = true;

            log.Info("缓存同步线程已标记为强制停止。");
        }
    }
}
